package com.hxminer.hxwebs.controller;

import com.hxminer.hxwebs.model.Result;
import com.hxminer.hxwebs.model.User;
import com.hxminer.hxwebs.repository.UserRepository;
import com.hxminer.hxwebs.service.UserService;
import com.hxminer.hxwebs.utils.ResultUitl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Author YRG
 * Created by on 2018/5/7.
 * Describe
 */
@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @GetMapping(value = "/users")
    public List<User> getUserList() {
        return userRepository.findAll();
    }

    /**
     * @param passwoard
     * @param username
     * @return
     */
    @PostMapping(value = "/users")
    public User userAdd(@RequestParam("password") String passwoard, @RequestParam("username") String username) {

        User user = new User();
        user.setPassword(passwoard);
        user.setUsername(username);
        return userRepository.save(user);
    }

    @PostMapping(value = "/people")
    public Result<User> userAdds(@Valid User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
//            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            return ResultUitl.error(1, bindingResult.getFieldError().getDefaultMessage());
        }
        user.setUsername(user.getUsername());
        user.setPassword(user.getPassword());
        return ResultUitl.success(userRepository.save(user));

    }


    @GetMapping(value = "/users/{id}")
    public User userFindOne(@PathVariable("id") Integer id) {
        return null;
    }

    //更新数据
    @PutMapping(value = "/users/{id}")
    public User userUpdate(@PathVariable("id") Integer id, @RequestParam("username") String username,
                           @RequestParam("password") String password) {

        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setPassword(password);
        return userRepository.save(user);
    }

    @DeleteMapping(value = "/users/{id}")
    public void userDelete(@PathVariable("id") Integer id) {
        userRepository.deleteById(id);
    }

    @PostMapping(value = "/users/{id}")
    public List<User> userListById(@PathVariable("id") Integer id) {

//        return userRepository.findByListId(id);
        return null;
    }

    /**
     * 插入多条语句
     */
    @PostMapping(value = "/users/mose")
    public void userMose() {

        userService.insetMose();
    }

}
